package com.itheima.chapter10.producerconsumer22;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/*
三条线程通信--优化
 */
public class Demo2 {
    public static void main(String[] args) {
        Printer1 p = new Printer1();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                        try {
                            p.print1();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                        try {
                            p.print2();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        p.print3();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }).start();
    }

}

class Printer1 {
    ReentrantLock lock = new ReentrantLock();
    //线程状态对象
    Condition c1 = lock.newCondition();
    Condition c2 = lock.newCondition();
    Condition c3 = lock.newCondition();
    int flag = 1;

    public void print1() throws InterruptedException {
        lock.lock();
        while(flag != 1) {
            c1.await();
        }
        System.out.print("喜");
        System.out.print("欢");
        System.out.println("你");
        flag = 2;
        c2.signal();
        lock.unlock();

    }

    public void print2() throws InterruptedException {
        lock.lock();
        if (flag != 2) {
            c2.await();
        }
        System.out.print("新");
        System.out.print("的");
        System.out.print("心");
        System.out.println("跳");
        flag = 3;
        c3.signal();
        lock.unlock();

    }

    public void print3() throws InterruptedException {
        lock.lock();
        if (flag != 3) {
            c3.await();
        }
        System.out.print("夜");
        System.out.print("的");
        System.out.print("尽");
        System.out.println("头");
        flag = 1;
        c1.signal();
        lock.unlock();

    }
}